package org.jsoncrypto;

import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.SecretKey;

import org.jsoncrypto.util.Base64;

public class JweRSA1_5 extends JcLibJwe_PK<RSAPublicKey, RSAPrivateKey> {
  // public JWERSA1_5(JSONObject header) {
  // super(header);
  // }

  public JweRSA1_5(JcLibEnc enc) throws JcBaseException {
    super(enc, JcBase.KW_ALG_RSA1_5);
  }

  public JweRSA1_5(String encrypted) throws JcBaseException {
    super(encrypted);
  }

  @Override
  public String encrypt(byte[] contentBytes, RSAPublicKey rsaPublicKey, String encodedJweIvSegment) throws JcBaseException {
    SecretKey contentEncryptionKey = generateContentEncryptionKey(null);
    String encodedJweEncryptedKey = JcBase.generateEncodedEncryptedKeyRSA15(rsaPublicKey, contentEncryptionKey);
    if (encodedJweIvSegment == null) {
      byte[] ivbytes = new byte[16];
      SecureRandom sr = new SecureRandom();
      sr.nextBytes(ivbytes);
      encodedJweIvSegment = Base64.encodeBytes(ivbytes, Base64.URL | Base64.DONT_BREAK_LINES);
    }
    return mEnc.encrypt(contentBytes, contentEncryptionKey, encodedJweEncryptedKey, encodedJweIvSegment);
  }

  @Override
  public byte[] decrypt(RSAPrivateKey rsaPrivateKey) throws JcBaseException {
    String encodedJweEncryptedKey = mEnc.getEncodedJweEncryptedKey();
    try {
      byte[] cipheredKeyBytes = Base64.decodeUrl(encodedJweEncryptedKey);
      byte[] secretKeyBytes = JcBase.decryptKey(rsaPrivateKey, JcBase.KW_ALG_RSA1_5, cipheredKeyBytes);
      return mEnc.decrypt(secretKeyBytes);

    } catch (Exception e) {
      throw new JcBaseException(e);
    }
  }

  @Override
  SecretKey generateContentEncryptionKey(RSAPublicKey unusedParameter) throws JcBaseException {
    return mEnc.generateRandomContentEncryptionKey();
  }

  @Override
  String generateEncodedEncryptedKey(RSAPublicKey rsaPublicKey, SecretKey contentEncryptionKey) throws JcBaseException {
    return JcBase.generateEncodedEncryptedKeyRSA15(rsaPublicKey, contentEncryptionKey);
  }

}
